

<div class="container-fluid">
    <div style="clear: both;">
        <input type="hidden" id="sid" value="{{ .id }}">
    </div>

    <div id="terminal"></div>
</div>


<link rel="stylesheet" href="/static/plugins/xterm/xterm.css" />
<script src="/static/plugins/xterm/xterm.js"></script>
<script>
    var term = new Terminal({
        rendererType: "canvas", //渲染类型
        rows: 40, //行数
        convertEol: true, //启用时，光标将设置为下一行的开头
        scrollback:10,//终端中的回滚量
        disableStdin: false, //是否应禁用输入。
        cursorStyle: 'underline', //光标样式
        cursorBlink: true, //光标闪烁
        theme: {
            foreground: 'yellow', //字体
            background: '#060101', //背景色
            cursor: 'help',//设置光标
        }
    });


    term.open(document.getElementById('terminal'));
    var url = "ws://"+window.location.host+"/admin/serverinfo/ssh";
    var ws = new WebSocket(url);
    ws.onopen = function() {
        console.log("connect ...");
        var  object = {};
        object['msg_type'] = 1;
        object['token'] = '';
        object['server_id'] = Number.parseInt(document.getElementById("sid").value);
        object['command'] = '';
        var firstmsg = JSON.stringify(object);
        ws.send(firstmsg);
    };
    ws.onclose = function() {
        //链接失败
        lightyear.notify("链接失败,服务已断开", 'danger', 100, 'mdi mdi-emoticon-devil', 'top', 'center');
    };
    var cmd = ''
    ws.onmessage = function(ev) {

        term.write(ev.data)
        cmd=''
    };

    term.onKey(e => {
        const ev = e.domEvent
        const printable = !ev.altKey && !ev.altGraphKey && !ev.ctrlKey && !ev.metaKey
        if (ev.keyCode === 13) {

            var  object = {};
            object['msg_type'] = 2;
            object['token'] = '';
            object['server_id'] = Number.parseInt(document.getElementById("sid").value);;
            object['command'] =cmd;
            var msg = JSON.stringify(object);
            ws.send(msg);


        } else if (ev.keyCode === 8) {
            // Do not delete the prompt
            if (term._core.buffer.x > 2) {
                term.write('\b \b')
                cmd = cmd.substring(0,cmd.length-1)
            }
        } else if (printable) {
            cmd = cmd + e.key
            term.write(e.key);

        }
    });


    // if(e.key.length == 0) {
    //     return
    // }
    //
    // var  object = {};
    // object['msg_type'] = 2;
    // object['token'] = '';
    // object['server_id'] = '';
    // object['command'] =e.key;
    // var msg = JSON.stringify(object);
    // ws.send(msg);

</script>
